# -*- coding: UTF-8 -*-
# @ Author : 游于艺
# @ QQ : 58012007
# @ File: zy_day10_游于艺.py
# @ Time: 2018/2/22 15:36
import random
"""
  1.自定义一个异常类,当list内元素长度超过10的时候抛出异常
"""
class MyError(Exception):
    def __init__(self,msg):
        self.msg = msg
    def __str__(self):
        return self.msg

a_list = [i for i in range(random.randint(5,15))]
try:
    print("a_list的长度：",len(a_list))
    if len(a_list) > 10:
        raise MyError("list内元素长度超过10")
except MyError as e:
    print("异常！")
    print(e)
else:
    print("没有异常！")
finally:
    print("结束！")
"""
  2.思考如果对于多种不同的代码异常情况都要处理,又该如何去处理,自己写一个小例子
"""
def fun1(s):
    return fun2(s) * 2
def fun2(s):
    return 10 / int(s)
try:
    fun1(0)
except Exception as e:
    print("异常\n",e)
finally:
    print("结束！")

"""
  3.try-except和try-finally有什么不同,写例子理解区别
"""
# 如第一题，try-finally，不管有没有异常都会执行finally中的代码，try-except只有接受异常时才执行except中代码
"""
  4.写函数，检查传入字典的每一个value的长度，如果大于2，那么仅仅保留前两个长度的内容，并将新内容返回给调用者 dic = {“k1”: "v1v1","k2":[11,22,33}}
"""
def get_two_dict(value):
    two_value = {}
    count = 0
    for i, v in value.items():
        if count >= 2:
            break
        two_value[i] = v
        count += 1
    return two_value
def get_two_set(value):
    if len(value)<=2:
        return value
    else:
        return set(list(value)[:2])

def check_dic(dic):
    # 优先判断是否是字典
    if not isinstance(dic, dict):
        raise MyError('输入的参数不是字典')

    result = {}
    for key, value in dic.items():
        if len(value) <= 2:
            result[key] = value
        elif isinstance(value, (str, list, tuple)):
            result[key] = value[:2]
        elif isinstance(value, dict):
            result[key] = get_two_dict(value)
        elif isinstance(value, set):
            result[key] = get_two_set(value)

    return result
try:
    dic = {"k1":"v1v1","k2":[11,22,33],"k3":{"a":1,"b":2,"c":3,"d":4},"k4":{1,2,3,4}}
    print(check_dic(dic))
except Exception as e:
    print("异常")
    print(e)